﻿using PidKeyReptile.Desktop.Helper;
using PidKeyReptile.Desktop.Pages.Crawler;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PidKeyReptile.Desktop.CrawlTask
{
    public class Jike_Info : GetWeb, ICapture
    {
        private CrawlerManagerViewModel crawler;

        public Jike_Info(CrawlerManagerViewModel crawler) : base(crawler)
        {
            this.crawler = crawler;
        }

        public async Task CaptureAsync(string url)
        {
            string rootHttp = "https://jike.info";
            try
            {
                //首页数据
                var docIndex = GetHtml(url, "");

                //新文章列好
                var newArticle = docIndex?.DocumentNode?.SelectNodes("//*[@id='content']/div[2]/div[1]/ul/li");
                if (newArticle == null) return;
                foreach (var li in newArticle)
                {
                    await Task.Delay(1000);
                    var allChildDiv = li.Descendants("div");
                    //获取文章URl
                    var articleUrl = allChildDiv.FirstOrDefault()?.ChildNodes["h2"]?.ChildNodes["a"]?.Attributes["href"]?.Value;
                    //如果有评论获取定位评论位置
                    var lastCoord = allChildDiv?.LastOrDefault()?.ParentNode.Descendants("a");
                    if (lastCoord.Any())
                    {
                        articleUrl = lastCoord.ToList()?[1].Attributes["href"]?.Value;
                    }
                    var articleHtml = GetHtml(rootHttp + articleUrl, "");
                    var txt = articleHtml?.DocumentNode?.SelectSingleNode("//*[@id='content']/div[2]/div[1]/ul")?.InnerText;
                    if (txt == null) continue;
                    await ParseAsync(txt);
                }
            }
            catch (Exception ex)
            {
                _crawler.LogText += $"{DateTime.Now}JieKe采集错误{ex.Message}\r\n";
                Console.WriteLine($"{DateTime.Now}采集错误{ex.Message}");
            }
            if (KeyList.Count == 0) return;
            int xx = await Db.Insertable(KeyList).ExecuteCommandAsync();
            _crawler.LogText += $"JieKe成功入库：{xx}条数据\r\n";
            Console.WriteLine($"成功入库：{xx}条数据");
        }
    }
}
